/*
 * @Author: zhuxiaoyi
 * @Date: 2023-12-29 14:36:11
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-01-22 17:42:39
 * @Description:
 */
import { Provide, Config } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { ITaskOptions } from '../interface';
import { Repository } from 'typeorm';
import { Task } from '../entity/task.entity';
import { CommonUtils } from '../utils/CommonUtils';
import { exec, ExecException } from 'child_process';

@Provide()
export class TaskService {
  @InjectEntityModel(Task)
  taskModel: Repository<Task>;

  @Config('appURL')
  appURL: string;

  @Config('platform')
  platform: string;


  async createTask(taskParam: ITaskOptions) {
    let task = new Task();
    task.imageFile = taskParam.imageFile;
    task.ruleFile = taskParam.ruleFile;
    task.progress = 0;
    task.status = '0';
    const taskResult = await this.taskModel.save(task);
    if (taskResult) {
      await this.runTask(task);
    }
    return taskResult;
  }

  async queryTask(id: number) {
    let task = await this.taskModel.findOne({
      where: {
        id: id,
      },
    });
    console.log('First photo from the db: ', task);
    return task;
  }

  async runTask(task: ITaskOptions) {
    let taskToUpdate = await this.taskModel.findOne({
      where: {
        id: task.id,
      },
    });

    this.taskModel.save(taskToUpdate);
    let Speed = 1024 * 1024 * 0.2;
    const fileSize = await CommonUtils.getFileSize(
      task.imageFile
    );

    let percentage = this.calculateProgressPerSecond(fileSize, Speed);
    let command;
    if (this.platform == 'windows') {
      command = `${this.appURL} -p ${task.imageFile},501;0;;;50;${task.ruleFile};4;class;`;
    } else {
      command = `${this.appURL} -p ${task.imageFile}#501%0%%%50%$${task.ruleFile}%4%class%`;
    }
    this.runCommond(command, taskToUpdate, percentage);
  }

  calculateProgressPerSecond(
    fileSizeInBytes: number,
    processingSpeedBytesPerSecond: number
  ): number {
    // 计算每秒中处理的字节数
    const bytesProcessedPerSecond = processingSpeedBytesPerSecond;

    // 计算总共需要多少秒处理完成
    const totalTimeInSeconds = fileSizeInBytes / bytesProcessedPerSecond;

    // 计算每秒中应返回的进度
    const progressPerSecond = 100 / totalTimeInSeconds;

    return progressPerSecond;
  }

  async runCommond(command: string, taskToUpdate: any, percentage: number) {
    taskToUpdate.progress = 1;
    taskToUpdate.status = '1'; //执行中
    let timer = setInterval(() => {
      if (taskToUpdate.progress < 95) {
        taskToUpdate.progress += percentage;
        if (taskToUpdate.progress > 95) taskToUpdate.progress = 95;
        this.taskModel.save(taskToUpdate);
      } else {
        clearInterval(timer);
      }
    }, 500);
    exec(
      command,
      (error: ExecException | null, stdout: string, stderr: string) => {
        if (error) {
          taskToUpdate.progress = 100;
          taskToUpdate.status = '2'; //执行成功
          this.taskModel.save(taskToUpdate);
          clearInterval(timer);
        }
      }
    );
  }
}
